import requests
from threading import Thread
from multiprocessing import Process, Lock, Queue
import time


def request_bilibili(index, lock):
    url = "https://www.bilibili.com/"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"
    }
    response = requests.get(url=url, headers=headers)
    print(response)
    with lock:
        with open("test.log", "a", encoding="utf-8") as f:
            f.write(str(response) + ":" + str(index) + "\n")

zero = 0
lock2 = Lock()
def math_test():
    global zero
    number = 2
    while number<10000000:
        number**=2
        with lock2:
            zero += 1
            zero -= 1
    print("math_test done")

def save_to_queue(index, my_queue):
    my_queue.put(index)

if __name__ == '__main__':
    start_time = time.time()
    thread_array = []
    lock = Lock()
    for i in range(10):
        t = Thread(target=request_bilibili, args=(i, lock))
        thread_array.append(t)
        t.start()
    for t in thread_array:
        t.join()
    end_time = time.time()
    print(f"加锁多线程获取10次bilibili首页运行了{end_time-start_time} s")

    start_time2 = time.time()
    process_array = []
    for j in range(10):
        p = Process(target=math_test)
        process_array.append(p)
        p.start()
    for p in process_array:
        p.join()
    end_time2 = time.time()
    print(f"加锁多进程运行10次计算密集型程序math_test用了{end_time2-start_time2} s, zero = {zero}")

    start_time3 = time.time()
    process_array2 = []
    my_queue = Queue()
    for k in range(10):
        p2 = Process(target=save_to_queue, args=(k, my_queue))
        process_array2.append(p2)
        p2.start()
    for p2 in process_array2:
        p2.join()
    for l in range(10):
        print(my_queue.get())
    end_time3 = time.time()
    print(f"使用queue进行多线程通信用了{end_time3-start_time3} s")
